package server.java.autoduel.Player;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.sun.sgs.app.ClientSession;
import com.thoughtworks.xstream.XStream;

/**
 * Provides a set of players blueprints for the game to work with
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 */
public class PlayerFactory {

	/**
	 * The relative path to the player xml file
	 */
	private final static String data_file = "/data/player/Player.xml";

	/**
	 * The player loaded from xml
	 */
	private static Player player;

	/**
	 * Loads up player data from the server filesystem
	 * 
	 * @param currentDir
	 *            the current directory we are in
	 * @throws IOException
	 */
	public static void loadPlayer(String currentDir) throws IOException {
		final File playerFile = new File(currentDir + PlayerFactory.data_file);
		final FileInputStream reader = new FileInputStream(playerFile);
		final byte[] buf = new byte[(int) playerFile.length()];

		reader.read(buf);
		reader.close();
		final XStream xstream = new XStream();
		xstream.alias("Player", Player.class);
		PlayerFactory.player = (Player) xstream.fromXML(new String(buf));
	}

	/**
	 * Provides the requested player to the caller with a new name and session
	 * 
	 * @param name
	 *            the new name for the player
	 * @param session
	 *            the new session for the player
	 * @return
	 */
	public static Player providePlayer(String name, ClientSession session) {
		return PlayerFactory.player.copy(name, session);
	}
}